﻿using System.Reflection;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.Core;
using TaleWorlds.Localization;
using TaleWorlds.MountAndBlade;

namespace MarriageFertility.Helpers;

internal static class ConversationUtils
{
    private const BindingFlags NonPublicInstance = BindingFlags.Instance | BindingFlags.NonPublic;
    
    public static ConversationManager GetConversationManager(CampaignGameStarter campaignGameStarter)
    {
        var field = campaignGameStarter.GetType().GetField("_conversationManager", NonPublicInstance);
        return field?.GetValue(campaignGameStarter) as ConversationManager;
    }

    public static void UpdatePlayerCharacterBodyProperties(Hero hero, BodyProperties properties, bool isFemale)
    {
        ReflectUtils.ReflectPropertyAndSetValue("StaticBodyProperties", properties.StaticProperties, hero);
        hero.Weight = properties.Weight;
        hero.Build = properties.Build;
        hero.UpdatePlayerGender(isFemale);
    }

    public static void ChangeCurrentCharaObject(CampaignGameStarter campaignGameStarter, Hero hero)
    {
        var conversationManager = GetConversationManager(campaignGameStarter);
        if (conversationManager?.ListenerAgent is not Agent agent) 
            return;

        // 更新角色对象
        var charField = typeof(Agent).GetField("_character", NonPublicInstance);
        charField?.SetValue(agent, hero.CharacterObject);

        // 更新身体属性
        UpdatePlayerCharacterBodyProperties(hero, agent.BodyPropertiesValue, hero.CharacterObject.IsFemale);

        // 更新角色名称
        if (agent.Name != null)
        {
            var newName = new TextObject($"\"{agent.Name}\" {hero.Name}");
            hero.SetName(newName, newName);
            
            var nameField = typeof(Agent).GetField("_name", NonPublicInstance);
            nameField?.SetValue(agent, newName);
        }
    }
}